package cn.tedu.micro.demo.rabbitmq;

import com.rabbitmq.client.*;
import com.rabbitmq.client.impl.AMQImpl;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
@Slf4j
public class MyConsumer {
    private Channel channel;
    @Before
    public void createChannel() {
        try {
//            1.创建连接工厂-工厂模式 创建连接的过程
            ConnectionFactory connectionFactory = new ConnectionFactory();
//            2.给工厂提供连接属性ip地址、端口号、用户名、密码
            connectionFactory.setHost("192.168.8.100");
            connectionFactory.setPort(5672);
            connectionFactory.setUsername("admin");
            connectionFactory.setPassword("123456");
//            3.新建一个连接
            Connection connection = connectionFactory.newConnection();
//            4.创建通道短连接
            channel = connection.createChannel();
        } catch (Exception e) {
            log.error("创建通道失败");
        }
    }
    @Test
    public void receiveMessage() {
        try {
//            回调方法,deliver(交付);用于处理消费者信息的处理
            DeliverCallback deliver = new DeliverCallback(){
                @Override
                public void handle(String consumerTag, Delivery message) throws IOException {
//                    解析消息对象(反序列化)
//                    byte[] body = message.getBody();
//                    String msg = new String(body);
//                    log.info("消费者01获得消息{}",msg);
                    log.info("消费者拒绝演示");
                    channel.basicReject(message.getEnvelope().getDeliveryTag(),false);

                }
            };
            CancelCallback cancel = new CancelCallback() {
                @Override
                public void handle(String consumerTag) throws IOException {

                }
            };
//            queue
            channel.basicConsume("biz_queue",false,deliver,cancel);
//            channel.basicCancel();消息取消订阅处理
        } catch (IOException e) {
            log.error("接收消息失败");
        }
        while (true);
    }

}
